<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/8/2
 * Time: 10:45
 */

namespace app\api\controller;

use app\api\model\Coupon as M;
use think\Db;

class Coupon extends Base
{


    public function index(){
        $m=new M();
        $goods_id= input('goods_id');
        $openid = input('openid');

        //获取用户
        $member=db('member')->where('program_openid',$openid)->find();
        $data=[];
        //获取优惠券
        $coupon= $m->where('coupon_userange',$goods_id)->whereOr('coupon_userange','999999')->where('coupon_status',2)
            ->field('coupon_id,coupon_discount,coupon_usecondition,
           etart_usetime,end_usetime,coupon_quantity,coupon_types,receive_limit,coupon_alreadyreceived')->select();
        //判断是否领取


        if(!empty($coupon)){

            foreach ($coupon as $v){

                if ($v['end_usetime']<time()){
                    $data=[];
                }else{

                    $v['full_reduction']='';
                    //获取优惠券记录
                    $coupondetails=  db('coupondetails')->where('member_id',$member['member_id'])->where('coupon_id',$v['coupon_id'])->count();
                    if($coupondetails==$v['receive_limit']){
                        $v['receive']=2;
                    }else{
                        $v['receive']='';
                    }
                    $v['validityperiod']=date('Y-m-d',$v['etart_usetime']).'---'.date('Y-m-d',$v['end_usetime']);

                    if($v['coupon_types']==1){

                        $v['coupon_discount']=$v['coupon_discount'];
                        $v['full_reduction']='';
                    }else if ($v['coupon_types']==2){
                        $v['full_reduction']= $v['coupon_discount'];
                        $v['coupon_discount']='';
                    }
                    $v['shuliang']=$v['coupon_quantity']-$v['coupon_alreadyreceived'];
                    $data[]=[
                        "coupon_id"=>$v['coupon_id'],
                        "discount"=>$v['coupon_discount'],//折扣
                        "full_reduction"=>$v['full_reduction'],//满减
                        "coupon_usecondition"=>$v['coupon_usecondition'],//使用条件
                        'validityperiod'=>$v['validityperiod'],//有效期
                        "coupon_quantity"=>$v['shuliang'],//数量
                        "receive"=>$v['receive'],//是否已领取判断
                    ];
                }

            }
        }
        $shu=[];


        if ($data){
            $shu=[
                'code'=>0,
                'msg'=>'ok',
                'data'=>$data
            ];
        }else{
            $shu=[
                'code'=>0,
                'msg'=>'错误',
                'data'=>''
            ];
        }

        return json_encode($shu);
    }




    public function receive(){
        $shu=[];
        //商品ID
        $goods_id=  input('goods_id');
        //   openid
        $openid=input('openid');
        //优惠券ID
        $coupon_id=input('coupon_id');
        $gen1= db('coupon')->where('coupon_id',$coupon_id)->find();
        if (($gen1['coupon_quantity']-$gen1['coupon_alreadyreceived'])<=0){
            $g= db('coupon')->where('coupon_id',$coupon_id)->update(['coupon_status'=>3]);
            $shu=[
                'code'=>0,
                'msg'=>'领取失败，旅行红包抢光了，下次再来吧！',
            ];
            return json_encode($shu);
        }

        Db::startTrans();
        try{
            //获取用户信息
            $member=db('member')->where('program_openid',$openid)->find();
            //对领取记录入库
            $da=db('coupondetails')->insert([
                'member_id'=>$member['member_id'],
                'coupon_id'=>$coupon_id,
                'starttime'=>time()
            ]);
            //
            $shu=db('coupondetails')->where('coupon_id',$coupon_id)->count();
            $gen= db('coupon')->where('coupon_id',$coupon_id)->update(['coupon_alreadyreceived'=>$shu]);
            // 提交事务
            Db::commit();

            $shu=[
                'code'=>0,
                'msg'=>'领取成功',
            ];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $shu=[
                'code'=>0,
                'msg'=>'领取失败',
            ];
        }


        return json_encode($shu);


    }



    public function following(){//查询当前商品下可用的优惠券
        $d=[];
        $goods_id= input('goods_id');
        $openid=input('openid');
        $member=db('member')->where('program_openid',$openid)->find();
//          $d= db('coupondetails')
//            ->alias('d')
//              ->where('d.member_id',$member['member_id'])
//              ->where('d.usestatus',0)
//              ->join('coupon a','a.coupon_id=d.coupon_id')
//              ->where('a.coupon_userange',$goods_id)
//              ->where('a.coupon_status',2)
//              ->whereOr('a.coupon_userange','999999')
//              ->field('a.*,d.id,d.starttime as lingqushijian')
//            ->select();

        $c= db('coupondetails')->where('member_id',$member['member_id'])->where('usestatus',0)->select();
        foreach ($c as $s){
            $g=  db('coupon')->where('coupon_id',$s['coupon_id'])->select();
            foreach ($g as $t){
                if ($t['coupon_userange']==$goods_id || $t['coupon_userange']=='999999' ){
                    if ($t['end_usetime']>time()){
                        $d[]=[
                            'id'=>$s['id'],
                            'coupon_discount'=>$t['coupon_discount'],
                            'coupon_types'=>$t['coupon_types'],
                            'end_usetime'=>$t['end_usetime'],
                            'etart_usetime'=>$t['etart_usetime'],
                            'coupon_usecondition'=>$t['coupon_usecondition'],
                        ];
                    }else{
                        db('coupondetail4233s')->where('id',$s['id'])->update([
                            'usestatus'=>2
                        ]);
                    }
                }
            }

        }
        $data=[];
        $shu=[];

        if (!empty($d)){
            foreach ($d as $v) {

                if ($v['end_usetime'] < time()) {
                    $data = [];
                } else {


                    if ($v['coupon_types'] == 1) {

                        $v['coupon_discount'] = $v['coupon_discount'];
                        $v['full_reduction'] = '';
                    } else if ($v['coupon_types'] == 2) {
                        $v['full_reduction'] = $v['coupon_discount'];
                        $v['coupon_discount'] = '';
                    }
                    $data[] = [
                        "coupon_id" => $v['id'],
                        "discount" => $v['coupon_discount'],//折扣
                        "full_reduction" =>(int)$v['full_reduction'],//满减
                        "validityperiod" => date('Y-m-d', $v['etart_usetime']) . '-' . date('Y-m-d', $v['end_usetime']),//使用条件
                        "coupon_usecondition" => $v['coupon_usecondition'],//使用条件
                    ];
                }
            }
            $shu=[
                'code'=>0,
                'msg'=>'查询成功',
                'data'=>$data
            ];

        }else{
            $shu=[
                'code'=>0,
                'msg'=>'没有旅行红包可用',
            ];
        }







        return json_encode($shu);
    }





}